const query = require('../model/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config/index')

// 通过username查找用户信息

exports.getUserInfoByName = async (req, res, next) => {
  const { username } = req.body
  const sqStr = `select * from user_info where username=?`
  const result = await query(sqStr, username)
  if (result.length !== 1) return res.cc('用户名错误', 99999)
  req.result = result[0] // 把结果传递给下一个处理函数
  next()
}

// 登录(post)
exports.login = (req, res, next) => {
  const { password } = req.body
  const result = req.result

  // 判断密码是否一致
  // username 前端加密后再校验密码
  //   const _password = bcrypt.compareSync(password, result.password)
  if (password !== result.password) return res.cc('密码错误', 99999)
  console.log(result)
  // 为token移除密码
  const userInfo = { ...result, password: '' }
  // 生成token (expiresIn 有效期)
  const tokenStr = jwt.sign(userInfo, config.jwtSecretKey, { expiresIn: config.expiresIn })
  //
  result.token = tokenStr
  res.cc('success', 0, result)
}

exports.getUserInfoIsByName = async (req, res, next) => {
  const { username } = req.body
  const sqStr = `select * from user_info where username=?`
  const result = await query(sqStr, username)
  //   console.log(res);
  if (result.length) return res.cc('已存在该用户', 99999)
  req.result = result[0] // 把结果传递给下一个处理函数
  next()
}

/**
 * @func register
 * @desc 注册
 * @param {username} 用户名
 * @param {password} 密码
 */
exports.register = async (req, res, next) => {
  const { username, password } = req.body
  //   const sqStr = `select * from user_info where username=?`
  const sqStr = `insert into user_info(username,password) values ('${username}','${password}')`
  const result = await query(sqStr)
  if (result.length) return res.cc('注册失败', 9999)
  res.cc('success', 0, null)
}
